//file.js 负责处理各个离线数据的内容格式
import { read, write } from './io'


class ObjectData {
	originData = {}
	async getData(filePath) {
		//TODO: 处理文件还不存在的情况
		const fileContent = await read(filePath)
		try{
			return JSON.parse(fileContent)
		}
		catch(e){
			return {}
		}
		
	}
	async setData(data, filePath){
		const textData = JSON.stringify(data)
		await write(filePath, textData)
	}
}

class   extends Array {
	constructor(filePath){
		super()
		this.filePath = filePath
	}
	async getData() {
		if(this.length>0) return
		//TODO: 处理文件还不存在的情况
		const fileContent = await read(this.filePath)
		try{			
			const dataInFile = JSON.parse(fileContent)
			this.push(...dataInFile)
			return this
		}catch(e){
			this.splice(0, this.length)
			return this
		}
	}
	async setData(data){
		this.splice(0, this.length, ...data)
		const textData = JSON.stringify(data)
		await write(this.filePath, textData)
	}
}
